<template>
    <a-modal v-bind:open="visible" @ok="handleUpdateUserInfo" @cancel="handleCancel" :confirm-loading="confirmLoading">
        <div style="display: flex;">
            <a-menu mode="inline" @click="handleMenuClick" v-model:selectedKeys="current" :items="items" style="width: 70px; font-size: medium; font-weight: bolder;" />
            <div v-if="current[0] == 'userInfo'">
                <a-upload
                    v-model:file-list="fileList"
                    name="avatar"
                    list-type="picture-card"
                    class="avatar-uploader"
                    :show-upload-list="false"
                    :customRequest="handleUpload"
                    :before-upload="beforeUpload"
                    @change="handleChange"
                    style="margin-left: 180px;"
                >
                    <img :src="formState.avatar" alt="avatar" width="100px" height="100px"/>
                </a-upload>
                <br/>
                <br/>
                <a-form
                    style="width: 500px;"
                    :model="formState"
                    :rules="rules"
                    name="basic"
                    :label-col="{ span: 8 }"
                    :wrapper-col="{ span: 10 }"
                    autocomplete="off"
                    @finish="handleUpdateUserInfo"
                >   
                    <a-form-item
                        label="昵称"
                        name="username"
                    >
                        <a-input v-model:value="formState.username" show-count :maxlength="50"/>
                    </a-form-item>

                    <a-form-item
                        label="手机号"
                        name="phone"
                    >
                        <a-input v-model:value="formState.phone" show-count :maxlength="11"/>
                    </a-form-item>

                    <a-form-item :wrapper-col="{ span: 14, offset: 10 }">
                        <a-button type="primary" html-type="submit">修改</a-button>
                    </a-form-item>
                </a-form>
            </div>
            <div v-else>
                <SystemMessage />
            </div>
        </div>
        <template #footer>
        </template>
    </a-modal>
</template>

<script lang="ts">
import SystemMessage from './systemMessage.vue'
export default {
    name: 'UserInfo',
    props: {
        visible: {
            type: Boolean,
            default: false,
        },
    },
    components: {
        SystemMessage
    }
};
</script>

<script lang="ts" setup>
import { h, ref, reactive, toRaw } from 'vue';
import type { Rule } from 'ant-design-vue/es/form';
import { message } from 'ant-design-vue';
import type { UploadChangeParam, UploadProps } from 'ant-design-vue';
import { MenuProps } from 'ant-design-vue';
import { UserOutlined, NotificationOutlined } from '@ant-design/icons-vue';
import { uploadAvatar, updateUserInfo } from '../../api/user_api'

interface FormState { // 表格类定义
    username: string;
    phone: string;
    avatar : string;
}
const formState = reactive<FormState>({// 表格对象
    username: '',
    phone: '',
    avatar: ''
});
const rules: Record<string, Rule[]> = { // 表格校验规则
    username: [{ required: true, message: '请输入昵称，长度不超过50', trigger: 'blur' }],
    phone: [{required: true, type: 'string', pattern: /^\d{11}$/, message:'请输入11位手机号', trigger: 'blur'}],
    password: [{type: 'string', required: true, pattern: /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d).{8,}$/, message: '密码必须包含大小写字母和数字，且至少8位长度', trigger: 'blur'}]
};
const emit = defineEmits(['updateSuccess', 'updateCancel', 'uploadSuccess'])
const confirmLoading = ref<Boolean>(false)
const fileList = ref([]);
const loading = ref<boolean>(false);
const uid = ref<string>('');
const items = ref<MenuProps['items']>([
{
  icon: () => h(UserOutlined),
  key: 'userInfo',
  label: '用户信息',
  title: '用户信息',
},
{
  icon: () => h(NotificationOutlined),
  key: 'systemMessage',
  label: '系统消息',
  title: '系统消息',
},
])
const current = ref<string[]>(['userInfo']);

const handleMenuClick: MenuProps['onClick'] = async menuInfo => {
};
const initUser = (data:any) =>{
    formState.phone = data.phone
    formState.username = data.username
    formState.avatar = data.avatar
    uid.value = data.uid
}
const handleUpload = async (info:any) => {
    loading.value=true
    const FormDatas = new FormData();
    FormDatas.append("file", info.file);
    await uploadAvatar(FormDatas)
    .then(
        function(response) {
            formState.avatar = response.data
            loading.value = false
            emit('uploadSuccess', response.data)
        }
    )
    .catch(
        function (response) {
            message.error(response.message)
        }
    )
    loading.value=false
}
const handleChange = (info: UploadChangeParam) => {
    if (info.file.status === 'uploading') {
        loading.value = true;
        return;
    }
    if (info.file.status === 'error') {
        loading.value = false;
        message.error('upload error');
    }
};
const beforeUpload: UploadProps['beforeUpload'] = file => {
    const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/jpg' || file.type === 'image/png';
    if (!isJpgOrPng) {
        message.error('You can only upload JPG file!');
    }
    const isLt2M = file.size / 1024 / 1024 < 10;
    if (!isLt2M) {
        message.error('Image must smaller than 10MB!');
    }
    return isJpgOrPng && isLt2M;
};
const handleCancel = () => {
    confirmLoading.value = false
    emit('updateCancel', {})
}
const handleUpdateUserInfo = async(value:any) => {
    confirmLoading.value = false
    value.uid = uid.value
    console.log(value)
    await updateUserInfo(value)
    .then(
        function(response) {
            emit('updateSuccess', value)
        }
    )
    .catch(
        function(response) {
            message.error(response.message)
        }
    )
}

defineExpose({
    initUser
})

</script>


<style scoped>
.avatar-uploader > .ant-upload {
  width: 50px;
  height: 50px;
}
.ant-upload-select-picture-card i {
  font-size: 32px;
  color: #999;
}

.ant-upload-select-picture-card .ant-upload-text {
  margin-top: 8px;
  color: #666;
}
</style>